
package org.beaconframework.ext.rs.jersey;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.beaconframework.ext.rs.WebResource;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource.Builder;

public class WebResourceFacade implements WebResource {

    com.sun.jersey.api.client.WebResource webResource;
    Client client;


    public WebResourceFacade(Client client,
            com.sun.jersey.api.client.WebResource wr) {
        this.webResource = wr;
        this.client = client;
        System.out.println("wr uri=" + wr.getURI());
    }


    private WebResource wrap(Builder b) {
        return new BuilderFacade(b);
    }


    private WebResourceFacade wrap(com.sun.jersey.api.client.WebResource wr) {
        return new WebResourceFacade(this.client, wr);
    }


    @Override
    public WebResource accept(MediaType... types) {

        return wrap(webResource.accept(types));

    }


    @Override
    public WebResource accept(String... types) {
        return wrap(webResource.accept(types));
    }


    @Override
    public WebResource acceptLanguage(String... languages) {
        return wrap(webResource.acceptLanguage(languages));
    }


    @Override
    public <T> T get(Class<T> responseClass) {

        try {

            return webResource.get(responseClass);
        } catch (UniformInterfaceException e) {
            throw new AdaptedUniformInterfaceException(e);
        }
    }


    @Override
    public URI getURI() {
        return webResource.getURI();

    }


    @Override
    public WebResource header(String s, Object... vals) {
        com.sun.jersey.api.client.WebResource wr = webResource;
        Builder b = null;
        for (Object val : vals) {
            if (b == null) {
                b = wr.header(s, val);
            } else {
                b = b.header(s, val);
            }
        }
        if (b != null) {
            return wrap(b);
        }
        return wrap(wr);
    }


    @Override
    public WebResource path(String path) {

        return wrap(webResource.path(path));
    }


    @Override
    public WebResource queryParam(String a, String b) {
        UriBuilder builder = webResource.getUriBuilder().queryParam(a, b);

        return wrap(client.resource(builder.build()));
    }

}
